﻿using Microsoft.Extensions.DependencyInjection;
using sentry.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace sentry.Tool
{
    public class ProcessManager
    {
        private Log _log = null;
        private TaskInfo _task = null;
        private string _outLog = null;
        private string _errorLog = null;
        public ProcessManager(TaskInfo task)
        {
            _log = App.Services.GetService<Log>();
            _task = task;
        }

        #region 启动任务
        /// <summary>
        /// 启动任务
        /// </summary>
        /// <param name="task">信息</param>
        /// <returns></returns>
        public Process RunTask()
        {
            int index = _task.Command.IndexOf(' ');
            string fileName = string.Empty;
            string command = string.Empty;
            if (index > 0)
            {
                //必须大于0
                fileName = _task.Command.Substring(0, index);
                command = _task.Command.Substring(index + 1, _task.Command.Length - index - 1);
            }
            else
            {
                fileName = _task.Command;
            }

            ProcessStartInfo startinfo = new ProcessStartInfo();
            //运行程序名
            startinfo.FileName = fileName;
            //设置工作目录
            startinfo.WorkingDirectory = _task.Directory;
            //关闭Shell
            startinfo.UseShellExecute = false;
            //重定向标准输入
            startinfo.RedirectStandardInput = true;
            //重定向标准输出
            startinfo.RedirectStandardOutput = true;
            //重定向错误输出
            startinfo.RedirectStandardError = true;
            //不显示窗口
            startinfo.CreateNoWindow = false;
            //startinfo.Arguments = "/C " + command;//"moncci.web.exe";//“/C”表示执行完命令后马上退出
            startinfo.Arguments = command;

            Process mproc = new Process();
            mproc.OutputDataReceived -= new DataReceivedEventHandler(mproc_OutputDataReceived);
            mproc.OutputDataReceived += new DataReceivedEventHandler(mproc_OutputDataReceived);
            mproc.ErrorDataReceived -= new DataReceivedEventHandler(mproc_ErrorDataReceived);
            mproc.ErrorDataReceived += new DataReceivedEventHandler(mproc_ErrorDataReceived);
            mproc.Exited -= new EventHandler(mproc_Exited);
            mproc.Exited += new EventHandler(mproc_Exited);

            mproc.EnableRaisingEvents = true;

            mproc.StartInfo = startinfo;

            //执行ver命令
            try
            {
                mproc.Start();
            }
            catch (Exception ex)
            {

                throw;
            }
            mproc.BeginOutputReadLine();
            mproc.BeginErrorReadLine();
            _outLog = Path.Combine(_task.Directory, "sentry_out.log");
            if (!File.Exists(_outLog))
            {
                using(FileStream fs = new FileStream(_outLog,FileMode.Create))
                {

                }
            }
            else
            {
                FileInfo fileInfo = new FileInfo(_outLog);
                long length = fileInfo.Length;
            }
            _errorLog = Path.Combine(_task.Directory, "sentry_error.log");
            if (!File.Exists(_errorLog))
            {
                using (FileStream fs = new FileStream(_errorLog, FileMode.Create))
                {

                }
            }
            else
            {
                FileInfo fileInfo = new FileInfo(_errorLog);
                long length = fileInfo.Length;
            }
            return mproc;
        }
        #endregion

        #region 退出
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mproc_Exited(object sender, EventArgs e)
        {
            _log.WriteLogCustom(_outLog, "任务退出");
        }
        #endregion

        #region 错误
        /// <summary>
        /// 错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mproc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {

            string value = e.Data;
            if (value != null)
            {
                if (!string.IsNullOrWhiteSpace(value))
                {
                    _log.WriteLogCustom(_errorLog, value);
                }
            }
        }
        #endregion

        #region 输出
        /// <summary>
        /// 输出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mproc_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(e.Data))
            {
                _log.WriteLogCustom(_outLog, e.Data);

            }
        } 
        #endregion

        #region 杀死任务
        /// <summary>
        /// 杀死任务
        /// </summary>
        /// <param name="task">任务</param>
        /// <returns></returns>
        public bool Kill(Process task)
        {
            try
            {
                if (task != null)
                {
                    task.Kill();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {

                return false;
            }
        } 
        #endregion
    }
}
